package com.subfg.common.util.redis;

import com.subfg.common.entity.excpetion.BusinessExceptionModel;
import com.subfg.common.util.common.StringUtil;
import lombok.SneakyThrows;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

@Service
public class LockService {
    private Logger log = LoggerFactory.getLogger(LockService.class);

    private static long BLOOMSIZE= 10000000L;

    private static double BLOOMERRORVALUE = 0.01;

    @Autowired
    private RedissonClient redissonClient;


    public <T> T executeWithLockThrows(String key, int waitTime, TimeUnit unit, SupplierThrow<T> supplier) throws Throwable {
        RLock lock = redissonClient.getLock(key);
        boolean lockSuccess = lock.tryLock(waitTime, unit);
        if (!lockSuccess) {
            throw new BusinessExceptionModel();
        }
        try {
            // 执行锁内的代码逻辑
            return supplier.get();
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @SneakyThrows
    public <T> T executeWithLock(String key, int waitTime, TimeUnit unit, Supplier<T> supplier) {
        return executeWithLockThrows(key, waitTime, unit, supplier::get);
    }

    public <T> T executeWithLock(String key, Supplier<T> supplier) {
        return executeWithLock(key, -1, TimeUnit.MILLISECONDS, supplier);
    }

    @FunctionalInterface
    public interface SupplierThrow<T> {

        /**
         * Gets a result.
         *
         * @return a result
         */
        T get() throws Throwable;
    }




    /**
     * 将单个字符添加进布隆过滤器
     * @param bloomName
     * @param addContent
     */
    public void add(String bloomName, String addContent) {
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(bloomName);
        if (!StringUtil.isEmpty(addContent) && !bloomFilter.contains(addContent))  {
            bloomFilter.add(addContent);
        }
    }

    /**
     * 将单个字符添加进布隆过滤器
     * @param bloomFilter
     * @param addContent
     */
    public void add(RBloomFilter bloomFilter, String addContent) {
        if (!StringUtil.isEmpty(addContent) && !bloomFilter.contains(addContent)) {
            bloomFilter.add(addContent);
        }
    }

    /**
     * 是否初始化
     * @param bloomName
     * @return
     */
    public RBloomFilter<String> isInitRB(String bloomName) {
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(bloomName);
        try {
            long size = bloomFilter.getSize();
            log.info("过滤器==>>>{} 初始化! 长度为==>>>{}, 现已初始化", bloomName, size);
        } catch (Exception e) {
            bloomFilter.tryInit(BLOOMSIZE, BLOOMERRORVALUE);
        }
        return bloomFilter;
    }



    /**
     * 向布隆过滤器添加数据
     * @param bloomName         过滤器名称
     * @param list              需要添加进过滤器的数据
     */
    public void addAll(String bloomName, List<String> list) {
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(bloomName);
        // 判断该过滤器是否初始化过, 如没有初始化则初始化数据
        try {
            long size = bloomFilter.getSize();
            log.info("过滤器==>>>{} 初始化! 长度为==>>>{}, 现已初始化", bloomName, size);
        } catch (Exception e) {
            log.info("过滤器==>>>{} 未初始化!, 现已初始化", bloomName);
            bloomFilter.tryInit(BLOOMSIZE, BLOOMERRORVALUE);
        }
        for(String str: list) {
            if (!StringUtil.isEmpty(str) && !bloomFilter.contains(str))  {
                bloomFilter.add(str);
            }
        }
    }

    /**
     *  过滤字符是否存在本系统中, 存在一定的误判率, 布隆过滤器
     * @param bloomName
     * @param verifyContent
     * @return
     */
    public boolean contains(String bloomName, String verifyContent) {
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(bloomName);
        return bloomFilter.contains(verifyContent);
    }
}
